<?php
/**
 * +----------------------------------------------------------------------
 * | 九月科技-ztuc.cn
 * +----------------------------------------------------------------------
 *                      .::::.
 *                    .::::::::.            | AUTHOR: siyu
 *                    :::::::::::           | EMAIL: ztucke@ztuc.cn
 *                 ..:::::::::::'           | DATETIME: 2020/01/31
 *             '::::::::::::'
 *                .::::::::::
 *           '::::::::::::::..
 *                ..::::::::::::.
 *              ``::::::::::::::::
 *               ::::``:::::::::'        .:::.
 *              ::::'   ':::::'       .::::::::.
 *            .::::'      ::::     .:::::::'::::.
 *           .:::'       :::::  .:::::::::' ':::::.
 *          .::'        :::::.:::::::::'      ':::::.
 *         .::'         ::::::::::::::'         ``::::.
 *     ...:::           ::::::::::::'              ``::.
 *   ```` ':.          ':::::::::'                  ::::..
 *                      '.:::::'                    ':'````..
 * +----------------------------------------------------------------------
 */
/**
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/3/14
 * Time: 17:18
 */
namespace app\lnadmin\controller;
use app\core\InitController;
use think\facade\View;
use think\facade\Db;
use think\facade\Filesystem;
use app\common\Common;
use app\lnadmin\controller\Upload;
use app\lnadmin\model\admin\User as UserModel;
use app\lnadmin\model\admin\Lnadmin as LnadminModel;
use app\lnadmin\model\admin\Image;
use app\lnadmin\model\admin\UserToken;
/**
 * 用户
 * Class User
 * @package app\controller\index
 */
class User extends InitController
{
      //列表详情
    public function index_json($limit='15')
    {
        $param = $this->request->param();
        $user = new UserModel();
        if (isset($param['subscribe'])) {  
            if ($param['subscribe']==0) {
            $user = $user->hidden(['salt','level','bio','money','score','successions','maxsuccessions','loginip','token','prev_time',])->where('status',$param['subscribe']);
        }else{
            $user = $user->whereLike('mobile|email|username|qq','%'.$param['subscribe'].'%');
          }
        }
        if(!empty($param['status'] == '1')){
        $list = $user->order('login_time desc')->where('status','0')->hidden(['salt','level','bio','money','score','successions','maxsuccessions','loginip','token','prev_time',])->paginate($limit);
        }else{
         $list = $user->order('id asc')->hidden(['salt','level','bio','money','score','successions','maxsuccessions','loginip','token','prev_time',])->paginate($limit);   
        }
        if (!empty($list)) {
            // 获取图片
            foreach ($list as $key => $val) {
                $val['headimgurl'] = Image::image($val['id'], Upload::TYPE_USER);
                $list[$key]['login_time'] = date('Y-m-d H:i:s', $val['login_time']);
            }
        }

        $this->result($list);
    }
    // 列表
    public function list()
    {
        return View::fetch('user');
    }

    // 新增
    public function add()
    {      
        if ($this->request->isPost()) {
            $param = $this->request->param();
                 //验证规则
            $verify = input('_verify', true);
            if($verify!='0'){
                try{
                    $this->validate($param, ['captcha|验证码'=>'captcha']);
                    $this->validate($param, 'register');
                }catch (\Exception $e){
                    $this->error($e->getMessage());
                }
            }   
            if (isset($param['expire_time'])) unset($param['expire_time']);
            $param['openid']   =isset($param['openid'])?base64_decode($this->request->param('openid')):"";
            $param['token']    = Common::token();
            $param['salt']     = Common::pwdMd5($param['password'])['salt'];
            $param['password'] = Common::pwdMd5($param['password'])['password'];
        $res = UserModel::add($param); 
        add_admin_log('add', '会员数据');// 记录行为日志
         return $res ? $this->success(true,0,__('login was successful')) : $this->error(__('Registration failed'));
    }
           return $this->fetch('saveUser');
  }

    // 删除
    public function del()
    {
        
        if ($this->request->isPost()) { 
            $param = $this->request->param();
            $result = UserModel::destroy($param['id']);
            if ($result == true) { 
            add_admin_log('del', '会员数据');// 记录行为日志
                return $this->success('', '', '删除成功');
            }
        }
    } 
   // 编辑
    public function edit()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            if(!empty($param['expire_time'])){
            $model = UserModel::with('userToken')->where(['id' => $param['id']])->find();
             if (empty($model->userToken->token)) {
            $map = ['user_id' => $model->id, 'token' => $model->token, 'expire_time' => turn_time($param['expire_time']), 'verification_time'=>time()];   // 30天 
            UserToken::create($map);
                }else{
            UserToken::update(['expire_time' => turn_time($param['expire_time'])], ['user_id' => $param['id']]);
              }
            }else{ 
            unset($param['expire_time']);//删除$param['expire_time'] 
            }
            $verify = input('_verify', true);
            
                 //验证规则
            if($verify!='0'){
                try{
                    $this->validate($param, 'profile');
                }catch (\Exception $e){
                   $this->error($e->getMessage());
                }
            }
             // 密码不填则是原始密码
            if (!empty($param['password'])) { 
            $param['salt'] = Common::pwdMd5($param['password'])['salt'];
            $param['password'] = Common::pwdMd5($param['password'])['password'];
            }else{
            unset($param['password']);//删除密码
            }
           $param['exp_time'] = time();
           $edit = UserModel::edit($param);
          
        add_admin_log('edit', '会员数据');// 记录行为日志
        return $edit ? $this->saveSuccess() : $this->error();
   
    }
        return view::fetch('saveUser', [
            'data' => UserModel::with('userToken')->where('id', input('id'))->find(), 
            'img' => Image::where(['table_id' => input('id'), 'types' => Upload::TYPE_USER])->force('images')->find(),
         ]);
    }
    
}